package com.ruoyi.web.controller.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.h1wUtils.QiniuUtils;
import com.ruoyi.entity.domain.Comic;
import com.ruoyi.entity.domain.Image;
import com.ruoyi.entity.service.IComicService;
import com.ruoyi.entity.service.IImageService;
import com.ruoyi.entity.service.IOptionService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.web.cq.DownloadUtil;
import com.ruoyi.web.cq.MailUtil;
import com.ruoyi.web.cq.WebUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import javax.jws.WebResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static com.ruoyi.common.core.domain.AjaxResult.success;

@RestController
@RequestMapping("/ano")
@Api(tags = "ano接口")
public class AnoController extends BaseController {

    @Autowired
    private IOptionService optionService;
    @Autowired
    private IImageService imageService;
    @Autowired
    private IComicService comicService;

    @ApiOperation("测试")
    @GetMapping("/aTest")
    public void aTest() throws Exception {
        MailUtil se = new MailUtil(false);
        File affix = new File("D:/1.gif");
        se.doSendHtmlEmail("今日推荐", "测试", "32011222@qq.com", affix);
    }

    @ApiOperation("爬取")
    @GetMapping("/aClimb")
    public void aClimb(
            @RequestParam(defaultValue = "0") @ApiParam(value = "开始", defaultValue = "0") Long start,
            @RequestParam(defaultValue = "0") @ApiParam(value = "结束", defaultValue = "0") Long end
    ) {
        String url = "https://zh.yyhentai.com/g/"; //地址
        if (start == 0)
            start = comicService.getMaxId();
        if (end == 0){
            String webResult = WebUtil.GetUrl("https://zh.yyhentai.com/");
            webResult = webResult.substring(webResult.indexOf("<a href=\"/g/")).substring(12);
            webResult = webResult.substring(0,webResult.indexOf("/"));
            end = Long.valueOf(webResult);
        }
        while (end >= start) {
            System.out.println(start + " / " + end);
            Comic comic = comicService.getComicById(start);
            Boolean createFlag = false;
            if (comic == null) {
                comic = new Comic();
                comic.setId(start);
                createFlag = true;
            }
            try {
                String webResult = webResult = WebUtil.GetUrl(url + start);
                String webRoman = webResult.substring(webResult.indexOf("<h1>") + 4, webResult.indexOf("</h1>"));
                String webTitle = webResult.substring(webResult.lastIndexOf("<h1>") + 4, webResult.lastIndexOf("</h1>"));
                String tempResult = webResult.substring(webResult.indexOf("<section id=\"tags\">") + 19);
                String webTags = tempResult.substring(0, tempResult.indexOf("</section>")).replaceAll("\t", "").replaceAll("<.*?>", " ");
                while (webTags.contains("  "))
                    webTags = webTags.replace("  ", " ");
                comic.setComicCode(start);
                comic.setComicTitle(webTitle);
                comic.setComicRoman(webRoman);
                comic.setComicTags(webTags);
            } catch (Exception e) {
                start++;
                if (createFlag)
                    comicService.addComic(comic);
                continue;
            }
            start++;
            if (createFlag)
                comicService.addComic(comic);
            else
                comicService.setComic(comic);
        }
        System.out.println("Climb over");
    }

    @ApiOperation("修复")
    @GetMapping("/aFix")
    public void aFix(
    ) {
        String url = "https://zh.yyhentai.com/g/"; //地址
        List<Comic> list = comicService.list(new QueryWrapper<>(new Comic() {{
            setComicCode(0l);
        }}));
        int length = list.size();
        for (int i = 1; i < length; i++) {
            System.out.println(i + " / " + length);

            Comic comic = comicService.getComicById(list.get(i).getId());
            try {
                String webResult = webResult = WebUtil.GetUrl(url + comic.getId());
                String webRoman = webResult.substring(webResult.indexOf("<h1>") + 4, webResult.indexOf("</h1>"));
                String webTitle = webResult.substring(webResult.lastIndexOf("<h1>") + 4, webResult.lastIndexOf("</h1>"));
                String tempResult = webResult.substring(webResult.indexOf("<section id=\"tags\">") + 19);
                String webTags = tempResult.substring(0, tempResult.indexOf("</section>")).replaceAll("\t", "").replaceAll("<.*?>", " ");
                while (webTags.contains("  "))
                    webTags = webTags.replace("  ", " ");
                comic.setComicCode(comic.getId());
                comic.setComicTitle(webTitle);
                comic.setComicRoman(webRoman);
                comic.setComicTags(webTags);
            } catch (Exception e) {
                continue;
            }
            comicService.setComic(comic);
        }
        System.out.println("Fixed over");
    }


    @ApiOperation("检查剩余次数")
    @GetMapping("/checkLoadTimes")
    public Map forseLoadImage(
    ) {
        String webUrl = "https://api.lolicon.app/setu/?apikey=" + optionService.getOption("ApiKey").getOptionValue() + "&keyword=abcabc";
        String webResult = WebUtil.GetUrl(webUrl);
        String countResult = webResult.substring(webResult.indexOf("\"quota\"") + 7);
        countResult = countResult.substring(0, countResult.indexOf(","));
        String timeResult = webResult.substring(webResult.indexOf("\"quota_min_ttl\"") + 15);
        timeResult = timeResult.substring(0, timeResult.indexOf(","));
        String result = "当前剩余额度为 " + countResult + "，下次回复剩余时间为 " + timeResult;
        return AjaxResult.success(result);
    }

    @ApiOperation("强加载图片")
    @GetMapping("/forseLoadImage")
    public Map forseLoadImage(
            @RequestParam(defaultValue = "0") @ApiParam(value = "status", defaultValue = "0") Integer status
    ) {
        List<Image> list = imageService.list(new QueryWrapper<>(new Image() {{
            setPicStatus(status);
        }}));
        Integer count = 0;
        for (Image image : list) {
            try {
                DownloadUtil.download(RuoYiConfig.getProfile(), image.getPicMas());
                image.setPicStatus(1);
                image.setPicPath("/profile" + image.getPicMas().substring(image.getPicMas().lastIndexOf("/")));
                imageService.updateById(image);
                count++;
            } catch (Exception e1) {
                try {
                    DownloadUtil.download(RuoYiConfig.getProfile(), image.getPicUrl());
                    image.setPicStatus(1);
                    image.setPicPath("/profile" + image.getPicUrl().substring(image.getPicUrl().lastIndexOf("/")));
                    imageService.updateById(image);
                    count++;
                } catch (Exception e2) {
                    image.setPicStatus(2);
                    image.setPicPath("");
                    imageService.updateById(image);
                }
            }
        }
        return AjaxResult.success(count);
    }

    @ApiOperation("缓存图片")
    @GetMapping("/loadImage")
    public String loadImage(
            @RequestParam(defaultValue = "") @ApiParam(value = "keyword", defaultValue = "") String keyword,
            @RequestParam(defaultValue = "1") @ApiParam(value = "times", defaultValue = "1") Integer times
    ) throws UnsupportedEncodingException {
        if (keyword == null)
            keyword = "";
        if (keyword != "")
            try {
                keyword = "&keyword=" + WebUtil.encode(keyword);
            } catch (Exception e) {
            }
        Integer countAll = 0;
        Integer countLoad = 0;
        Integer countPart = 0;
        Integer countDown = 0;
        Integer countCur = 0;
        String webResult = "";
        for (int i = 0; i < times; i++) {
            String webUrl = "https://api.lolicon.app/setu/?r18=2&num=10&apikey=" + optionService.getOption("ApiKey").getOptionValue() + keyword;
            String tempResult = WebUtil.GetUrl(webUrl);
            webResult = webResult + "= " + tempResult + "\n";
            List<Map> tempList = (List<Map>) ((Map) JSON.parse(tempResult)).get("data");
            countAll = countAll + tempList.size();
            for (Map temp : tempList) {
                Image image = new Image();
                image.setPicId(new Long(String.valueOf(temp.get("pid"))));
                image.setPicPage(new Integer(String.valueOf(temp.get("p"))));
                image.setUserId(new Long(String.valueOf(temp.get("uid"))));
                if (imageService.list(new QueryWrapper<Image>(image)).size() == 0) {
                    image.setPicTitle(String.valueOf(temp.get("title")));
                    image.setUserName(String.valueOf(temp.get("author")));
                    image.setPicR18(Boolean.valueOf(String.valueOf(temp.get("r18"))) ? 1 : 0);
                    image.setPicUrl(String.valueOf(temp.get("url")));
                    image.setPicMas(String.valueOf(temp.get("url")).replace("original", "master").replace(".jpg", "_master1200.jpg").replace(".png", "_master1200.jpg"));
                    image.setPicWidth(new Long(String.valueOf(temp.get("width"))));
                    image.setPicHeight(new Long(String.valueOf(temp.get("height"))));
                    image.setPicTags(temp.get("tags").toString());
                    imageService.save(image);
                    countLoad++;
                    if (image.getPicR18() == 0)
                        countPart++;
                    try {
                        DownloadUtil.download(RuoYiConfig.getProfile(), image.getPicMas());
                        image.setPicStatus(1);
                        image.setPicPath("/profile" + image.getPicMas().substring(image.getPicMas().lastIndexOf("/")));
                        imageService.updateById(image);
                        countDown++;
                    } catch (Exception e1) {
                        try {
                            DownloadUtil.download(RuoYiConfig.getProfile(), image.getPicUrl());
                            image.setPicStatus(1);
                            image.setPicPath("/profile" + image.getPicUrl().substring(image.getPicUrl().lastIndexOf("/")));
                            imageService.updateById(image);
                            countDown++;
                        } catch (Exception e2) {
                            image.setPicStatus(2);
                            image.setPicPath("");
                            imageService.updateById(image);
                        }
                    }
                }
                countCur++;
                System.out.println("===>>> " + countCur + " / " + countAll);
            }
        }
        String result = "Get " + countAll + ", New " + countLoad + ", Load " + countPart + ".";
        System.out.println("======>>>>>>\n" + webResult + "= " + result + "\n======>>>>>>");
        return result;
    }

}
